//
//  UITextField+Category.m
//  VICategory
//
//  Created by MN on 2022/12/29.
//

#import "UITextField+Category.h"
#import <objc/runtime.h>
@implementation UITextField (Category)

- (void)setVi_limitBlock:(void (^)(void))vi_limitBlock {
    objc_setAssociatedObject(self, @selector(vi_limitBlock), vi_limitBlock, OBJC_ASSOCIATION_COPY);
}

- (void (^)(void))vi_limitBlock {
    return objc_getAssociatedObject(self, @selector(vi_limitBlock));
}

- (void)vi_lengthLimit:(void (^)(void))limit {
    [self addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    self.vi_limitBlock = limit;
}

- (void)textFieldEditChanged:(UITextField *)textField {
    //获取高亮部分
    UITextRange *selectedRange = [textField markedTextRange];
    UITextPosition *position = [textField positionFromPosition:selectedRange.start offset:0];
    
    // 没有高亮选择的字，则对已输入的文字进行字数统计和限制
    if (!position){
        if (self.vi_limitBlock) self.vi_limitBlock();
    }
}
@end
